//initial state
const state = {
  //购物车商品集合
  goodItem: [],   //商品存储方式{good:data,num:11}需要将商品的数据存储起来，便于购物车页面的渲染
  checkState: false, //检查商品是否已添加
}

//getters
const getters = {
  //商品总数
  carTatalNum (state) {
    let sum = 0;
    for(let i=0; i<state.goodItem.length; i++){
      sum += state.goodItem[i].num;
    }
    return sum > 99 ? '99+': sum;
  }

}

//mutations
const mutations = {
  //商品添加到购物车
  addProductToCar(state,obj){
    //先检查购物车是否此商品
    // this.checkShopState (state,obj);
    if(state.checkState){
      for(let i=0; i<state.goodItem.length; i++){
        if(state.goodItem[i].good.id === obj.id){
          state.goodItem[i].num += 1;
        }
      }
    }else{
      let item = {
        good: obj,
        num: 1,
      };
      state.goodItem.push(item);
    }
  },
  //减少商品数量
  reduceShopNum (state,obj) {
    for(let i=0; i<state.goodItem.length; i++){
      if(state.goodItem[i].good.id === obj.id){
        state.goodItem.num -= 1;
        if(state.goodItem.num < 1){
          //当商品的数量为0，购物车中不渲染此商品
          state.goodItem.splice(i,1)
        }
      }
    }
  },
  //检查商品状态
  checkShopState (state,obj) {
    for(let i=0; i<state.goodItem.length; i++){
      if(state.goodItem[i].good.id === obj.id){
        state.checkState = true;
      }
    }
  }
}
//actions
const actions = {
  //向购物车中添加商品
  addProductToCar ({ commit }, obj) {
    commit('addProductToCar',obj);
  },
  //减少购物车中商品的数量
  reduceShopNum ({ commit },obj) {
    commit('reduceShopNum',obj);
  },
  //检查购物车是否有次商品
  checkShopState ({ commit },obj) {
    commit('checkShopState',obj);
  }
}


export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
} 




